<chat-input>
  <input type="text" placeholder="请输入问题" placeholder-class="input-placeholder" disabled={state.isSubmiting}
    onkeypress={handleKeyPress}></input>

  <script>
    export default {
      name: 'chat-input',
      version: '0.0.1',
      state: {
        isSubmiting: false,
      },
      onMounted() {
        console.log('input onMounted');
      },
      handleKeyPress(event) {
        if (event.keyCode === 13) {
          const text = event.target.value;
          if (!text) return;
          bus.emit('chat-box:add_message', ChatUtil.create({
            from: 'Me',
            content: text,
          }));
          event.target.value = '';

          const botMessage = ChatUtil.create({
            from: 'Bot',
            loading: true,
          });
          bus.emit('chat-box:add_message', botMessage);
          bus.emit('chat-box:update_message', {
            id: botMessage.id,
            message: {
              isLoading: true
            }
          });

          this.update({
            isSubmiting: true,
          });

          let content = '';
          const sse = new EventSource(`chat_stream?q=${text}`);
          sse.addEventListener("notice", (e) => {
            console.log('notice', e.data);
          })

          sse.addEventListener("update", (e) => {
            console.log('update', e.data);
          })

          sse.addEventListener("message", (e) => {
            console.log('message', e.data);
            bus.emit('chat-box:update_message', {
              id: botMessage.id,
              message: {
                isLoading: false,
                content: e.data
              }
            });
          });

          sse.addEventListener("error", (err) => {
            console.log('error', err);
            sse.close();
            bus.emit('chat-box:update_message', {
              id: botMessage.id,
              message: {
                isLoading: false,
                content: _.get(err, 'data') || _.get(err, 'message') || '未知错误'
              }
            });
            this.update({
              isSubmiting: false,
            });
            this.$('input', this.root).focus();
          });


        }
      }
    }
  </script>
  <style>
    chat-input {
      height: 60px;
      display: flex;
      padding: 8px 16px;
    }

    chat-input input {
      flex: 1;
      font-size: 16px;
      padding: 0 30px;
      background: #ffffff;
      border: 1px solid #dfe1e6;
      box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.08), 0px 0px 4px rgba(0, 0, 0, 0.08);
      border-radius: 30px;
    }

    chat-input input[disabled] {
      opacity: 0.5;
    }
  </style>
</chat-input>